import React, { useState, useEffect } from 'react';
import { NavBar, Tabs, Card, Tag, Button } from 'antd-mobile';
import { useNavigate, useSearchParams } from 'react-router-dom';
import axios from '../../axios';
import defaultProductImage from '../../assets/react.svg';
import './Com/Order.css';

// 订单数据类型
interface Order {
  orderId: string;
  productName: string;
  price: number;
  quantity: number;
  status: string;
  orderTime: string;
  paymentMethod: string;
  deliveryAddress: string;
  pickupCode?: string;
  completedTime?: string;
  refundReason?: string;
  refundAmount?: number;
  refundTime?: string;
}

const Order: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const orderType = searchParams.get('type') || 'all';
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

  const handleBack = (): void => {
    navigate(-1);
  };

  // 英文参数到中文状态的映射
  const paramToStatusMap: { [key: string]: string } = {
    'unpaid': '待付款',
    'undelivered': '待发货',
    'pickup': '待提货',
    'uncommented': '待评价',
    'refund': '退款/售后'
  };

  // 获取订单数据
  const fetchOrders = async () => {
    try {
      setLoading(true);
      
      // 从 localStorage 获取用户ID
      const yonghuId = localStorage.getItem('yonghuId');
      
      if (!yonghuId) {
        console.error('未找到用户ID，请重新登录');
        setLoading(false);
        return;
      }
      
      // 调用后端API获取用户数据
      const response = await axios.get(`http://localhost:3000/hy/yonghu/${yonghuId}`);
      
      if (response.data.code === 200 && response.data.data) {
        const userData = response.data.data;
        setOrders(userData.orders || []);
        console.log('获取到的订单数据:', userData.orders);
      } else {
        console.error('API返回错误:', response.data.message);
      }
    } catch (error) {
      console.error('获取订单数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 根据状态过滤订单
  const filterOrders = (status: string): Order[] => {
    if (status === 'all') {
      return orders;
    }
    
    // 将英文参数转换为中文状态
    const chineseStatus = paramToStatusMap[status];
    if (!chineseStatus) {
      return orders;
    }
    
    // 处理退款状态的特殊情况
    if (status === 'refund') {
      return orders.filter(order => 
        order.status === '退款中' || order.status === '已退款'
      );
    }
    
    return orders.filter(order => order.status === chineseStatus);
  };

  // 格式化时间
  const formatTime = (timeString: string): string => {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取状态标签颜色
  const getStatusColor = (status: string): string => {
    switch (status) {
      case '待付款':
        return '#ff4d4f';
      case '待发货':
        return '#faad14';
      case '待提货':
        return '#52c41a';
      case '待评价':
        return '#1890ff';
      case '退款中':
      case '已退款':
        return '#8c8c8c';
      default:
        return '#8c8c8c';
    }
  };

  // 获取状态文本（直接返回中文状态）
  const getStatusText = (status: string): string => {
    return status || '未知状态';
};

  // 获取订单操作按钮
  const getOrderActions = (order: Order) => {
    const actions = [];
    
    switch (order.status) {
      case '待付款':
        actions.push(
          <Button
            key="pay"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到支付页面
              navigate('/my/payment', { 
                state: { 
                  order: {
                    orderId: order.orderId, //订单号
                    productName: order.productName, //商品名称
                    price: order.price, //商品价格
                    quantity: order.quantity, //商品数量
                    orderTime: order.orderTime //订单时间
                  }
                } 
              });
            }}
          >
            去付款
          </Button>
        );
        break;
      case '待发货':
        actions.push(
          <Button
            key="refund"
            size="small"
            style={{
              color: '#1677ff',
              background: 'transparent',
              border: 'none'
            }}
            onClick={() => {
              // 跳转到申请退款页面
              navigate('/my/refund-apply', {
                state: {
                  order: order
                }
              });
            }}
          >
            申请售后
          </Button>
        );
        break;
      case '待提货':
        // 添加申请退款按钮
        actions.push(
          <Button
            key="refund"
            size="small"
            style={{
              color: '#1677ff',
              background: 'transparent',
              border: 'none'
            }}
            onClick={() => {
              // 跳转到申请退款页面
              navigate('/my/refund-apply', {
                state: {
                  order: order
                }
              });
            }}
          >
            申请售后
          </Button>
        );
        actions.push(
          <Button
            key="pickup"
            size="small"
            color="primary"
            onClick={() => {
              // 跳转到提货码页面
              navigate('/my/ma', {
                state: {
                  userInfo: {
                    userId: localStorage.getItem('yonghuId'),
                    nickname: '用户',
                    phone: '13800138000'
                  },
                  pickupCodes: [{
                    orderId: order.orderId,
                    productName: order.productName,
                    pickupCode: order.pickupCode || 'PC' + Date.now(),
                    orderTime: order.orderTime,
                    deliveryAddress: order.deliveryAddress
                  }]
                }
              });
            }}
          >
            查看提货码
          </Button>
        );
        break;
      case '待评价':
        actions.push(
          <Button
            key="evaluate"
            size="small"
            color="primary"
            onClick={() => {
              navigate('/my/remark', {
                state: {
                  order: order
                }
              });
            }}
          >
            去评价
          </Button>
        );
        break;
    }
    
    return actions;
  };

  const tabs = [
    { key: 'all', title: '全部' },
    { key: 'unpaid', title: '待付款' },
    { key: 'undelivered', title: '待发货' },
    { key: 'pickup', title: '待提货' },
    { key: 'uncommented', title: '待评价' },
    { key: 'refund', title: '退款/售后' }
  ];

  // 渲染订单列表
  const renderOrderList = (status: string) => {
    const filteredOrders = filterOrders(status);
    
    if (loading) {
      return <div className="loading">正在加载...</div>;
    }

    if (filteredOrders.length === 0) {
      const statusText = status === 'all' ? '订单' : (paramToStatusMap[status] || status);
      return (
        <div className="empty-state">
          <p>暂无{statusText}</p>
        </div>
      );
    }

    return (
      <div className="order-list">
        {filteredOrders.map(order => (
          <Card key={order.orderId} className="order-card">
            {/* 订单头部 */}
            <div className="order-header">
              <div className="order-header-left">
                <span className="order-id">订单号: {order.orderId}</span>
                <span className="order-time">{formatTime(order.orderTime)}</span>
              </div>
              <Tag color={getStatusColor(order.status)} className="order-status">
                {getStatusText(order.status)}
              </Tag>
            </div>
            
            {/* 商品信息 */}
            <div className="product-section">
              <div className="product-image">
                <img src={defaultProductImage} alt={order.productName} />
              </div>
              <div className="product-details">
                <h3 className="product-name">{order.productName}</h3>
                <div>
                  <div className="product-price">
                    <span className="price">¥{order.price.toFixed(2)}</span>
                  </div>                   
                  <div className="product-specs">
                    <span className="quantity">x{order.quantity}</span>
                  </div>
                </div>

              </div>
            </div>

            {/* 订单详情 */}
            <div className="order-info">
              {order.deliveryAddress && (
                <div className="info-item">
                  <span className="info-label">收货地址:</span>
                  <span className="info-value">{order.deliveryAddress}</span>
                </div>
              )}
              {order.pickupCode && (
                <div className="info-item">
                  <span className="info-label">提货码:</span>
                  <span className="info-value pickup-code">{order.pickupCode}</span>
                </div>
              )}
              {order.refundReason && (
                <div className="info-item">
                  <span className="info-label">退款原因:</span>
                  <span className="info-value">{order.refundReason}</span>
                </div>
              )}
            </div>

            {/* 订单底部 */}
            <div className="order-footer">
              <div className="order-total">
                <span className="total-label">实付款:</span>
                <span className="total-price">¥{(order.price * order.quantity).toFixed(2)}</span>
              </div>
              <div className="order-actions">
                {getOrderActions(order)}
              </div>
            </div>
          </Card>
        ))}
      </div>
    );
  };

  return (
    <div className="order-page">
      <NavBar onBack={handleBack}>
        我的订单
      </NavBar>
      
      <Tabs defaultActiveKey={orderType}>
        {tabs.map(tab => (
          <Tabs.Tab title={tab.title} key={tab.key}>
            {renderOrderList(tab.key)}
          </Tabs.Tab>
        ))}
      </Tabs>
    </div>
  );
};

export default Order;
